import React from 'react'
import marked from 'marked';
import 'bulma/css/bulma.min.css';
import 'github-markdown-css';
import './style.scss';

import editorbold from '../../assets/images/editor-bold.svg'

const IconImg = (props) => {
    let res = props.icon.replace('icon-', '') +'.svg'
    let resImg = require('../../assets/images/' + res)
    console.log(resImg.default)
    // let res = '../../assets/images/' + props.icon.replace('icon-', '') + '.svg'
    return (<img src={resImg.default} alt=""/>)
}

const IconButton = (props) => (
    <button className="button is-small" onClick={props.onClick}>
    <span className="icon is-small">
        <i className={`iconfont ${props.icon}`}><IconImg icon={props.icon}/></i>
    </span>
    </button>
);


class Markdown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            markdown: ''
        };
        this.ref = React.createRef();
        console.log('ctor');
    }

    componentDidMount() {
        console.log('mount');
        let content = window.localStorage.getItem('markdownContent');
        if (content) {
            this.setState({markdown: content});
        }
    }

    render() {
        console.log('render');
        let markdown = this.state.markdown;
        let html = marked(markdown);

        return (
            <div className="markdown">
                <div className="toolbar">
                    <IconButton icon="icon-editor-bold" onClick={() => this.onBold()}/>
                    <IconButton icon="icon-editor-italic"/>
                    <IconButton icon="icon-editor-underline"/>
                    <IconButton icon="icon-editor-list-bulleted"/>
                </div>
                <div className="body box">
                    <div className="editor">
                        <textarea ref={this.ref} className="textarea" value={markdown}
                                  onChange={e => this.onChange(e)}/>
                    </div>
                    <div className="preview markdown-body" dangerouslySetInnerHTML={{__html: html}}>
                    </div>
                </div>
            </div>
        );
    }

    onChange(e) {
        this.setValue(e.target.value);
    }

    onBold() {
        let el = this.ref.current;
        let start = el.selectionStart;
        let end = el.selectionEnd;
        let text = this.state.markdown.substring(start, end);

        // el.setRangeText('**' + text + '**');
        // el.setRangeText(`**${text}**`);
        // let event = new Event('change', { bubbles: true });
        // el.dispatchEvent(event);

        // single source of truth
        let markdown = this.state.markdown;
        markdown = markdown.substr(0, start) + '**' + text + "**" + markdown.substr(end);
        this.setValue(markdown);
    }


    setValue(markdown) {
        this.setState({markdown: markdown});

        window.localStorage.setItem('markdownContent', markdown);
    }
}


export default Markdown;